package controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.User;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 回写数据
 */
@Controller
public class WritebackData {
    /**
     * 通过response对象直接回写字符串
     *
     * @return 视图
     */
    @RequestMapping("/modelAndView05")
    public void response_ModelAndView05(HttpServletResponse response) {
        try {
            response.getWriter().print("You are writing back a message by Response");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过return语句直接回写字符串
     * 需要加@ResponseBody注解
     *
     * @return 视图
     */
    @ResponseBody //告知SpringMVC该方法不进行视图跳转，直接以HTTP请求体的方式进行数据响应
    @RequestMapping("/modelAndView06")
    public String response_ModelAndView06() {
        return "You are writing back a message by return statement";
    }

    /**
     * 回写json格式字符串
     *
     * @return 视图
     */
    @ResponseBody
    @RequestMapping("/modelAndView07")
    public String response_ModelAndView07() {
        try {
            User user = new User();
            user.setName("AnonyEast");
            user.setAddr("ChengDu");
            //使用json的转换工具将javabean转换为json格式字符串后返回
            ObjectMapper mapper = new ObjectMapper();
            String userInfo = mapper.writeValueAsString(user);
            return userInfo;//返回的是user对象的json格式字符串
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * SpringMVC自动将User对象转换成JSON格式字符串返回
     *
     * 需要在spring-mvc.xml中进行相关配置
     * 也可以添加<mvc:annotation-driven />，它自带jackson
     * @return User对象的json格式字符串
     */
    @ResponseBody
    @RequestMapping("/modelAndView08")
    public User response_ModelAndView08() {
        User user = new User();
        user.setName("XHH");
        user.setAddr("ZiGong");
        return user;
    }
}
